package com.bf.xpdd.service.impl;

import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.bf.xpdd.domain.ActivityBean;
import com.bf.xpdd.domain.ActivityGlobal;
import com.bf.xpdd.domain.ActivityRecordBean;
import com.bf.xpdd.domain.ActivitySettingBean;
import com.bf.xpdd.domain.BidCache;
import com.bf.xpdd.domain.FrontBean;
import com.bf.xpdd.domain.FrontBidRecord;
import com.bf.xpdd.domain.FrontDealRecord;
import com.bf.xpdd.domain.SiteBuyer;
import com.bf.xpdd.domain.SiteItem;
import com.bf.xpdd.exception.BaseException;
import com.bf.xpdd.persistent.iface.DaoFront;
import com.bf.xpdd.service.FrontService;
import com.bf.xpdd.service.TaobaoService;
import com.ibatis.sqlmap.client.SqlMapClient;

/**
 * 
 * 交互部分服务
 * 
 * @author Fantastic·
 * @version 1.0.0 2011-06-29
 * @since 1.0.0
 *
 */
@Component
public class FrontServiceImpl implements FrontService
{
	/** DB session */
	@Autowired
	private SqlMapClient sqlMapClient;
	
	/** dao */
	@Autowired
	private DaoFront daoFront;
	
	/** taobao service */
	@Autowired
	private TaobaoService taobaoService;
	
	/**
	 * {@inheritDoc}
	 */
	@Override
	public FrontBean findFrontActivity(String nick, int start, int end) throws BaseException
	{
		FrontBean front = new FrontBean();
		try 
		{
			//活动全局信息
			ActivityGlobal global = daoFront.queryActivityGlobal(sqlMapClient, nick);
			
			List<SiteItem> itemList = null;
			
			//如果全局时间小于当前时间 不展示商品
			if(global.getEndTime().getTime() - new Date().getTime() > 60000L)
			{
				//商品列表
				itemList = daoFront.queryGobalItem(sqlMapClient, nick, start, end);
			}
			
			List<FrontBidRecord> bidList;
			List<FrontDealRecord> dealList;
			
			if(null != itemList && !itemList.isEmpty())
			{
				//获取参加活动的商品信息
				StringBuilder builder = new StringBuilder();
				for(SiteItem item : itemList)
				{
					builder.append(item.getCode()).append(",");
				}
				String idStr = builder.substring(0, builder.length() - 1);
				itemList = taobaoService.findItemById(idStr);
				
				//获取出价记录
//				bidList = daoFront.queryTop5BidRecordByAct(sqlMapClient, nick);
				
				//获取成交记录
//				dealList = daoFront.queryTop5DealRecordByAct(sqlMapClient, nick);
				
			}
			else
			{
				itemList = new ArrayList<SiteItem>(0);
//				bidList = new ArrayList<FrontBidRecord>(0);
//				dealList = new ArrayList<FrontDealRecord>(0);
			}
			
			bidList = new ArrayList<FrontBidRecord>(0);
			dealList = new ArrayList<FrontDealRecord>(0);
			
			front.setRemainingTime(new Date(global.getEndTime().getTime() - new Date().getTime()));
			front.setRule("游戏规则");
			front.setNote(global.getNotice());
			front.setProtocol("活动协议");
			front.setItemList(itemList);
			front.setBidList(bidList);
			front.setDealList(dealList);
			
		} 
		catch (Exception e)
		{
			throw new BaseException("-6", "服务器繁忙, 请尝试刷新页面");
		}
		return front;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public FrontBean findFrontItemDetail(String sellerNick, String itemId)
			throws BaseException 
	{
		FrontBean front = new FrontBean();
		try 
		{
			//活动全局信息
			//ActivityGlobal global = daoFront.queryActivityGlobal(sqlMapClient, sellerNick);
			//获取商品所属活动信息
			ActivityBean activity = daoFront.queryActivityByItem(sqlMapClient, itemId);
			//ActivitySettingBean setting = daoFront.queryActivitySettingByItem(sqlMapClient, itemId);
			
			//商品列表
			//List<SiteItem> itemList = daoFront.queryGobalItem(sqlMapClient, sellerNick);
			List<SiteItem> itemList = this.taobaoService.findItemById(itemId);
			
			List<FrontBidRecord> bidList;
			//List<FrontDealRecord> dealList;
			
			if(null != itemList && !itemList.isEmpty())
			{
				//获取出价记录 v1.0.0中实际上是成交记录
				bidList = daoFront.queryTop5BidRecordByAct(sqlMapClient, sellerNick, itemId);
				
				//判断次数
				if(bidList.size() >= activity.getMaxNum())
				{
					throw new BaseException("该宝贝已参与人数已达上限");
				}
				
				//隐藏部分昵称
//				StringBuilder builder;
//				for(FrontBidRecord tempRecord : bidList)
//				{
//					builder = new StringBuilder();
//					builder.append(tempRecord.getNick().substring(0, 1)).append("****").append(tempRecord.getNick().substring(tempRecord.getNick().length() - 1, tempRecord.getNick().length()));
//					tempRecord.setNick(builder.toString());
//				}
				
				//获取成交记录
				//dealList = daoFront.queryTop5DealRecordByAct(sqlMapClient, sellerNick, itemId);
				
			}
			else
			{
				itemList = new ArrayList<SiteItem>(0);
				bidList = new ArrayList<FrontBidRecord>(0);
//				dealList = new ArrayList<FrontDealRecord>(0);
			}
			
			//dealList = new ArrayList<FrontDealRecord>(0);
			
			//front.setRemainingTime(new Date(new Date().getTime() - global.getBeginTime().getTime()));
			//front.setRule("游戏规则");
			//front.setNote(global.getNotice());
			//front.setProtocol("活动协议");
			front.setNote(activity.getNotice());
			front.setItemList(itemList);
			front.setBidList(bidList);
			//剩余时间
			front.setRemainingTime(new Date(activity.getEndTime().getTime() - new Date().getTime()));
			//front.setDealList(dealList);
			
		} 
		catch (SQLException e) 
		{
			throw new BaseException("初始化活动失败");
		}
		
		return front;
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public FrontBean bargain(long itemId, double price, int plan, SiteBuyer buyer) throws BaseException
	{
		FrontBean front = new FrontBean();
		BidCache bidCache = buyer.getBidMap().get(itemId + "");
		//TODO 直接从play界面请求 但没有砍价信息
		
		
		//获取讨价策略
		try 
		{
			ActivitySettingBean setting = this.daoFront.queryActivitySettingByItem(sqlMapClient, itemId + "");
			//首次是0
			if(bidCache.getBidCount() >= setting.getMaxCount())
			{
				//高于出价
				front.setDialogue("超过次数了, 只能按¥" + bidCache.getCurrentPrice());
				front.setExpression(1);
				return front;
			}
			SiteItem item = this.taobaoService.findItemById(itemId + "").get(0);
			double realPrice = Double.parseDouble(item.getPrice());
			double basePrice = realPrice * setting.getBaseLine() / 100;
			int ai = setting.getaI();
			double currentPrice = bidCache.getCurrentPrice();
			
			//dialogue -- 1 低于底线。2 高于原价。3 接受砍价。4 不接受砍价。 
			//表情 1 笑 2 思考 3 可怜
			
			if(price < basePrice)
			{
				front.setDialogue("实在太低了 " + setting.getFirstDialogue());
				//throw new BaseException("小于基准价格");
				front.setExpression(3);
			}
			else if(price > realPrice || price > currentPrice)
			{
				//高于原价
				front.setDialogue("比要价还高哦 " + setting.getForthDialogue());
				front.setExpression(1);
			}
			else
			{
				//保存出价
				bidCache.setBid(price);
				
				//策略 ＊ 0 5 10 15
				//次数 ＊ 10
				int bidCount = bidCache.getBidCount() + 1;
				double dealable = bidCache.getCurrentPrice();
				
				List<Integer> planList = new ArrayList<Integer>();
				planList.add(1);
				planList.add(2);
				planList.add(3);
				planList.add(4);
				Collections.shuffle(planList);
				String planDailogue;
				double addDiscount = 0.0d;
				if (plan == planList.get(0).intValue()) 
				{
					planDailogue = "你很有才!!! ";
					addDiscount = 0.15;
				} 
				else if(plan == planList.get(1).intValue())
				{
					planDailogue = "你说的很好!! ";
					addDiscount = 0.1;
				}
				else if(plan == planList.get(2).intValue())
				{
					planDailogue = "这样啊... ";
					addDiscount = 0.05;
				}
				else
				{
					planDailogue = "...... ";
				}
				//差额减少比例
				double discount = bidCache.getDiscount() + (bidCount * 0.1 + addDiscount) * ai / 10;
				bidCache.setDiscount(discount);
				
				//调整到实际预定折扣
				java.text.NumberFormat nf = java.text.NumberFormat.getNumberInstance();
				nf.setMaximumFractionDigits(3);
				
				//底线折扣
				double baseDis = setting.getBaseLine() / 100;
				//差额折扣每份
				double perDis = (1 - baseDis) / 10;
				//当前砍价后获得的折扣
				double bidDis = baseDis + (1 - baseDis) * (1 - discount);
				//成交折扣
				double taobaoDis;
				for(int i = 0; i < 10; i++)
				{
					taobaoDis = Double.parseDouble(nf.format(baseDis + perDis * i));
					if(bidDis < taobaoDis)
					{
						dealable = realPrice * taobaoDis;
						if(price < dealable)
						{
							bidCache.setTaobaoDiscount(taobaoDis);
							bidCache.setCurrentPrice(dealable);
						}
						break;
					}
				}
				
				bidCache.setBidCount(bidCache.getBidCount() + 1);
				
				if(dealable == realPrice)
				{
					//仍然等于原价
					front.setDialogue(setting.getForthDialogue() + "只能按￥" + dealable);
					front.setExpression(2);
				}
				else
				{
					//这个价格能接受么（四舍五入，保留一位小数
					DecimalFormat df = new DecimalFormat("#.0");
				
					front.setDialogue(planDailogue + setting.getThridDialogue() + " 就按￥" + df.format(dealable) + "成交！");
					front.setExpression(1);
				}
				
			}
			
		} 
		catch (SQLException e)
		{
			throw new BaseException("出价分析错误");
		}
		
		return front;
	}

	/**
	 * {@inheritDoc}
	 * @throws BaseException 
	 */
	@Override
	public ActivityRecordBean findActivityRecordInfoByItem(String itemId) throws BaseException
	{
		try 
		{
			return this.daoFront.queryActivityRecordInfoByItem(sqlMapClient, itemId);
		} 
		catch (SQLException e) 
		{
			throw new BaseException("查询商品成交记录相关信息失败");
		}
	}

}
